<template>
  <div class="book">
    <h1>书籍管理</h1>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 添加书籍区域 -->
        <el-col :span="2">
          <el-button
            type="primary"
            @click="dialogVisible = true"
            icon="el-icon-plus"
            :disabled="batchID.length == 0 ? false : true"
            >添加书籍</el-button
          >
        </el-col>
        <!-- 批量删除区域 -->
        <el-col :span="1.5">
          <el-button type="danger" @click="batchRemove">删除</el-button>
        </el-col>
        <!-- 搜索框 -->
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            @input="searchBooks(searchInpVal)"
            v-model="searchInpVal"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchBooks(searchInpVal)"
              v-preventReClick="1000"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 表格区域 -->
        <el-col>
          <el-table
            :data="showBookList.rows"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            max-height="660px"
          >
            <el-table-column type="selection" width="55px"> </el-table-column>
            <el-table-column label="序号" width="100px" align="center">
              <template slot-scope="scope">
                {{
                  scope.$index +
                  (queryInfo.currentPage - 1) * queryInfo.pagesize +
                  1
                }}
              </template>
            </el-table-column>
            <el-table-column label="封面">
              <template slot-scope="{ row }">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="
                    row.cover ||
                    'http://127.0.0.1:7001/public/upload/1618791425297.jpg'
                  "
                  @click="showBigImg(row.cover)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="书名"
              width="150px"
              show-overflow-tooltip
            >
              <template slot-scope="{ row }">
                《{{ row.name || "暂无数据" }}》
              </template>
            </el-table-column>
            <el-table-column prop="id" label="图书ID" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="类目">
              <template slot-scope="{ row }">
                {{ row.category || "暂无数据" }}
              </template>
            </el-table-column>
            <el-table-column label="出版日期" show-overflow-tooltip>
              <template slot-scope="{ row }">
                {{ row.createDate || "暂无数据" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="press"
              label="出版社"
              width="160px"
              show-overflow-tooltip
            >
              <template slot-scope="{ row }">
                {{ row.press || "暂无数据" }}
              </template>
            </el-table-column>
            <el-table-column label="作者" show-overflow-tooltip width="150px">
              <template slot-scope="{ row }">
                {{ row.author || "暂无数据" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="info"
              label="图书简介"
              width="200"
              show-overflow-tooltip
            >
              <template slot-scope="{ row }">
                {{ row.info || "暂无数据" }}
              </template>
            </el-table-column>
            <el-table-column label="价格/元" width="100px">
              <template slot-scope="{ row }">
                {{ row.price || "暂无数据" }}
              </template>
            </el-table-column>
            <el-table-column prop="operation" label="操作" width="200px">
              <template scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="putBook(scope.row)"
                  :disabled="batchID.length == 0 ? false : true"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="removeBook(scope.row.id)"
                  :disabled="batchID.length == 0 ? false : true"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <!-- 分页区域 -->
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.currentPage"
            :page-sizes="[7,10, 15, 20, 25]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="showBookList.count"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog title="封面" :visible.sync="showBigImgDialog" width="490px">
      <el-image
        style="width: 450px; height: 650px"
        :src="
          bigImgSrc || 'http://127.0.0.1:7001/public/upload/1618791425297.jpg'
        "
      ></el-image>
    </el-dialog>
    <!-- 对话框区域 -->
    <el-dialog
      title="操作"
      :visible.sync="dialogVisible"
      width="50%"
      @close="handleDialogClose"
    >
      <el-form
        ref="bookFormRef"
        :rules="bookFormRules"
        :model="showBookForm"
        label-width="80px"
      >
        <el-form-item label="书名" prop="name">
          <el-input v-model="showBookForm.name"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <!-- <el-input v-model="personalForm.userimg"></el-input> -->
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:7001/uploadbook"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="showBookForm.author"></el-input>
        </el-form-item>
        <el-form-item label="类目" prop="Category">
          <!-- <el-input v-model="showBookForm.Category"></el-input> -->
          <el-select
            v-model="showBookForm.category"
            placeholder="请选择图书类目"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in clazz"
              :key="index"
              :label="item.category"
              :value="item.category"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出版日期">
          <!-- <el-input v-model="showBookForm.createDate"></el-input> -->
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="showBookForm.createDate"
            style="width: 100%"
            value-format="yyyy-mm-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="出版社" prop="press">
          <el-input v-model="showBookForm.press"></el-input>
        </el-form-item>
        <el-form-item label="图书简介">
          <el-input type="textarea" v-model="showBookForm.info"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input type="number" v-model="showBookForm.price"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBookForm(showBookForm)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      queryInfo: {
        currentPage: 1, // 当前页码
        pagesize: 7, // 每页显示的行数
      },
      currentPageLocal:'',
      tableData: [], // 表格数据,
      // 控制对话框 展示 隐藏
      dialogVisible: false,
      // 公用 ID
      allId: "",
      // 批量删除
      batchID: "",
      // 查询参数对象
      searchInpVal: "",
      // 图片上传绑定 headers 绑定的空对象
      headers: {},
      // 封面路径
      imageUrl: "",
      // 表单验证规则
      bookFormRules: {
        // 书名
        name: [{ required: true, message: "请输入书名", trigger: "blur" }],
        // 作者
        author: [{ required: true, message: "请输入作者", trigger: "blur" }],
        // 请选择类目
        // Category: [{ required: true, message: "请选择图书类", trigger: "blur" }],
        // 出版社
        press: [{ required: true, message: "请输入出版社", trigger: "blur" }],
        // 价格
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
      },
      // 类目
      clazz: [],
      // // 控制单个删除按钮的禁用与启用
      // handleRemoveVisiable:true
      // 浅克隆 showBookForm 数据
      cloneBookForm: [],
      // 控制查看大图 展示 隐藏
      showBigImgDialog: false,
      // 大图 src
      bigImgSrc: "",
    };
  },
  created() {
    this.$store.dispatch("getBookList", this.queryInfo);
    this.getToken();
    this.getClazz();
  },
  computed: {
    ...mapGetters([
      // 书籍列表
      "showBookList",
      // 提交表单数据
      "showBookForm",
      // 书籍类
      "showClazz",
    ]),
  },
  methods: {
    // 获取类
    getClazz() {
      this.clazz = JSON.parse(window.localStorage.getItem("clazz"));
    },
    // 切换页码
    handleCurrentChange(newPage) {
      try {
        this.queryInfo.currentPage = newPage;
        // 判断搜索框是否有值
        // 1. 有 ： 搜索
        // 2. 没有 ： 所有值
        if (!this.searchInpVal) {
          this.$store.dispatch("getBookList", this.queryInfo);
        } else {
          this.searchBooks(this.searchInpVal);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 每页展示数据条数
    handleSizeChange(newSize) {
      try {
        this.queryInfo.pagesize = newSize;
        // 判断搜索框是否有值
        // 1. 有 ： 搜索
        // 2. 没有 ： 所有值
        if (!this.searchInpVal) {
          this.$store.dispatch("getBookList", this.queryInfo);
        } else {
          this.searchBooks(this.searchInpVal);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 点击编辑 展示对话框
    putBook(e) {
      try {
        this.dialogVisible = true;
        this.allId = e.id;
        let form = Object.assign({}, e);
        this.$store.commit("infoBookForm", form);
      } catch (e) {
        e;
      }
    },
    // 监听对话框关闭
    handleDialogClose() {
      try {
        this.dialogVisible = false;
        this.$store.commit("infoBookForm", {});
        this.$refs.bookFormRef.resetFields();
        this.allId = ""
      } catch (e) {
        console.log(e);
      }
    },
    // 点击确定 提交表单
    submitBookForm(e) {
      try {
        let clazz_id = this.clazz.find((item) => {
          return e.category == item.category;
        });
        this.$refs.bookFormRef.validate((valid) => {
          if (!valid) return this.$message.info("数据格式不完整");
          let paramsAdd = {
            name: e.name,
            price: e.price,
            createDate: e.createDate,
            Category: e.category,
            press: e.press,
            author: e.author,
            info: e.info,
            cover: this.imageUrl,
            clazz_id: clazz_id.id,
            currentPage: this.queryInfo.currentPage, // 当前页码
            pagesize: this.queryInfo.pagesize, // 每页显示的行数
          };
          if (!this.allId) {
            this.$store.dispatch("createBook", paramsAdd);
            this.$message.success("添加成功");
          } else {
            let params = {
              book: paramsAdd,
              id: this.allId,
              cover: this.imageUrl,
              currentPage: this.queryInfo.currentPage, // 当前页码
              pagesize: this.queryInfo.pagesize, // 每页显示的行数
              searchBook: this.searchInpVal, // 传入一个
            };
            this.$store.dispatch("putBook", params);
            this.$message.success("编辑成功");
            this.allId = "";
          }
          this.dialogVisible = false;
          // 清空图片路径
          this.imageUrl = "";
          // 清空下拉菜单数据
          this.clazz.category = "";
        });
      } catch (e) {
        e;
      }
    },
    // 点击删除
    removeBook(i) {
      try {
        this.$confirm("此操作将永远删除该图书，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            let params = {
              currentPage: this.queryInfo.currentPage, // 当前页码
              pagesize: this.queryInfo.pagesize, // 每页显示的行数
              i,
            };
            this.$store.dispatch("removeBook", params);
            this.$message.success("删除成功");
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      } catch (e) {
        console.log(e);
      }
    },
    // 批量删除
    batchRemove() {
      try {
        if (this.batchID.length == 0)
          return this.$message.info("请选择需要删除的书籍");
        this.$confirm("此操作将永远删除选中图书，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            for (let i = 0; i < this.batchID.length; i++) {
              let params = {
                currentPage: this.queryInfo.currentPage, // 当前页码
                pagesize: this.queryInfo.pagesize, // 每页显示的行数
                i: this.batchID[i],
              };
              this.$store.dispatch("removeBook", params);
            }
            this.$message.success("删除成功");
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      } catch (e) {
        console.log(e);
      }
    },
    // 搜索
    searchBooks(e) {
      try {
        setTimeout(() => {
          if (!e) return this.$store.dispatch("getBookList", this.queryInfo);
          let params = {
            book: e,
            queryInfo: this.queryInfo,
          };
          this.$store.dispatch("searchBook", params);
        }, 200);
      } catch (e) {
        console.log(e);
      }
    },
    // 监听多选框
    handleSelectionChange(e) {
      this.batchID = e.map((item) => {
        return item.id;
      });
    },
    // 获取 token 赋值给 data 中的headers
    getToken() {
      this.headers.Authorization = window.localStorage.getItem("token");
    },
    // 封面上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data.file;
    },
    // 图片上传之前 检测图片是否合格
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 点击封面 展示对话框
    showBigImg(e) {
      try {
        this.bigImgSrc = e;
        this.showBigImgDialog = true;
      } catch (e) {
        console.log(e);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.book {
  .el-card {
    margin-top: 20px;
    .el-table {
      max-height: 65vh;
      margin-top: 20px;
      // overflow: auto;
    }
    .el-pagination {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
    .searchInput {
      width: 200px;
      height: 40px;
    }
  }
}
// 找到子孙级组件的样式
.avatar-uploader/deep/.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>